#!/usr/bin/env python3
# 利用多线程加速分析

import json
import threading
import time

from spark import Package
from spark import Spark


def ReslovePackage(package, resloves) -> Package:
    desc = ""
    partdesc = False
    pkg = Package() # Package 是一个字典

    lines = package.split('\n')
    for line in lines:
        # print(line)
        if line.startswith(Spark.KEY_Description):
            # print("partdesc = TRUE")
            partdesc = True

        if partdesc:
            if line.startswith(Spark.KEY_Description):
                # print("if")
                pkg.setValue(line)
            elif line.startswith(' '):
                # print("elif")
                desc = desc + '\n' + line
            else:
                # print("else")
                pkg.setLongDescription(desc.strip())
                for key in Spark.KEYS:
                    if line.startswith(key):
                        pkg.setValue(line)
                partdesc = False
                # print("partdesc = False")

        if partdesc:
            # print("continue")
            continue

        for key in Spark.KEYS:
            if line.startswith(key):
                pkg.setValue(line)
    if partdesc:
        # 如果是最后一行，可能无法触发 for 循环内的结束层
        partdesc = False
        # print("partdesc = False")
        pkg.setLongDescription(desc.strip())
    resloves.add(pkg)
    return pkg


class ResloveList(list):
    ''' 一个带线程锁的 list'''
    _lock = threading.Lock()

    def add(self, pkg):
        '''带有自锁功能的函数'''
        self._lock.acquire()
        self.append(pkg)
        self._lock.release()


class ResloveWork(threading.Thread):
    '''解析工作 - 将使用线程进行运行'''
    started = False
    package = None
    _lock = threading.Lock()

    def __init__(self, package, resloves):
        self.package = package
        self.resloves = resloves
        self.func = ReslovePackage
        self.args = (self.package, self.resloves)
        super().__init__(target=self.func, args=self.args)

    def start(self):
        '''start 拥有自锁状态的启动函数'''
        self._lock.acquire()
        if self.started == False:
            super().start()
            self.started = True
        self._lock.release()

class ResloveWorkPool:
    '''解析池 - 将初始化分发解析任务'''
    workers = []
    resloves = ResloveList()

    def __init__(self):
        pass

    def append(self, packages):
        for package in packages:
            if len(package) < 20: continue
            self.workers.append(ResloveWork(package, self.resloves))

    def start(self):
        for worker in self.workers:
            worker.start()

    def wait(self):
        for worker in self.workers:
            worker.join()

if __name__ == '__main__':
    # 此外应该注意前面不能存在空格, LongDescription 除外
    package = '''\
Package: bytedance-feishu-stable
Architecture: amd64
Version: 4.11.6-2
Priority: optional
Section: default
Maintainer: Feishu Linux Team <contact@feishu.cn>
Installed-Size: 948715
Pre-Depends: dpkg (>= 1.14.0)
Depends: ca-certificates, libc6 (>= 2.18), libgcc1 (>= 1:3.0), libnss3 (>= 3.14), libx11-6 (>= 2:1.4.99.1), libxcb1, libxext6, wget, xdg-utils (>= 1.0.2)
Recommends: libu2f-udev, libvulkan1
Replaces: bytedance-feishu-alpha
Filename: store/chat/bytedance-feishu-stable/bytedance-feishu-stable_4.11.6-2_amd64.deb
Size: 241141444
MD5sum: 86f09aea09a7de7f17dc306211c3d277
SHA1: 328881e3f893b72ad6d79988ac796e9dfd0c6e29
SHA256: e53a94f29002c41f773aa32e5b726a54ec4f4088e92d3eebbbea010e7f8ff3f7
SHA512: 0583fc606b61770ee464406ce6a9eaed0e11e026bb4f357f9c1254e80f915d8e1b0c4fc208d4e45912db5909a89f6f8dbc9779f8224eecb0f0f97270bf5ef049
Description: 飞书(Feishu)
 飞书整合即时消息、日历、音视频会议、云文档、工作台等功能于一体，成就团队和个人，更高效、更愉悦。

'''

    # pkg = Package()

    # 1. 解析一个包信息
    # pkg = ReslovePackage(package)
    # print(pkg)

    # 2. 解析多个包信息
    # resloves = ResloveList()
    # with open('Packages', 'r') as f:
    #     packageinfos = [info.strip() for info in f.read().split('\n\n')]
    #     for info in packageinfos:
    #         resloves.add(ReslovePackage(info))

    # 2.1 打印解析包数量
    # print("已解析:",len(resloves))

    # 2.2 打印第一个包信息, indent=True 会改变 ensure_ascii 转换，所以要明确指定
    # print(json.dumps(resloves[0], indent=True, ensure_ascii=False))

    # real    0m0.318s
    # user    0m0.259s
    # sys     0m0.056s


    # 3. 多线程解析包信息
    resloves = ResloveList()
    resPool = ResloveWorkPool()

    with open('Packages', 'r') as f:
        packageinfos = [info.strip() for info in f.read().split('\n\n')]
        resPool.append(packageinfos)
        # for info in packageinfos:
            # resloves.add(ReslovePackage(info))
    resPool.start()
    resPool.wait()
    print("已解析:", len(resPool.resloves))

    # real    0m0.645s
    # user    0m0.515s
    # sys     0m0.103s

    

